from django.shortcuts import render,redirect,HttpResponse
from django import forms

#####################创建form表单  #####################
# from django.views import View

class LoginForm(forms.Form):
    username=forms.CharField(
        label='名字',
        required=True,
        min_length=3,
        max_length=10,
        widget=forms.TextInput(attrs={'class':'form-control'}),
        error_messages={
            'required':'用户名不能为空',
            'min_length':'长度不能小于5个字符',
            'max_length':'长度不能大于10个字符',
        }
    )
    email=forms.CharField(
        label='邮箱',
        required=True,
        max_length=50,
        widget=forms.TextInput( attrs={'class': 'form-control'} ),
        error_messages={
            'required': '用户名不能为空',
            'max_length': '长度不能大于50个字符',
        }
    )
#form表单
def login_form(request):
    if request.method=='GET':
        #     定义GET请求的方法GET请求
        form = LoginForm()
        return render( request, 'login.html', {'form': form} )

    else:
        # '定义post请求的方法post请求'
        # 将请求到的数据填充到LoginForm实例中
        form = LoginForm( request.POST )
        # 判断是否为有效表单
        if form.is_valid():
            # 使用form.cleaned_data获取请求的数据
            username = form.changed_data['username']
            email = form.cleaned_data['email']
            # 页面跳转至欢迎界面
            # return HttpResponse('app02/welcome',username=username)
            return HttpResponse( f'用户名:{username},邮箱:{email}' )
        else:
            # 验证失败 返回表单
            return render( request, 'login.html', {'form': form} )

